<script setup lang="ts">
import { CirclePlus, Remove } from '@element-plus/icons-vue'
import type { Config, ELECTRICITY_CONFIG_TYPES } from '@/mixins/MixinElectricPriceConfigs'

const props = defineProps<{
  type: ELECTRICITY_CONFIG_TYPES
  typeText: string
  list: Config[]
  initialChecked?: boolean
}>()
const emits = defineEmits<{
  (e: 'add', config: Config): void
  (e: 'remove', index: number): void
  (e: 'change', data: {
    configs: Config[]
    index?: number
    timerange?: TimeRange
  }): void
}>()

type TimeRange = [string, string]

const checked = ref(props.initialChecked)
const disabled = computed(() => !unref(checked))
const price = ref(props.list[0]?.price)
const timerangeArray = ref<TimeRange[]>([['', '']])

const [priceError, setPriceError] = useState(false)
const [errors, setErrors] = useState<boolean[]>([])

const configs = computed<Config[]>(() => {
  return unref(timerangeArray).map(v => ({
    startTime: v?.[0],
    endTime: v?.[1],
    type: props.type,
    price: Number(unref(price)) || '',
  }))
})

function listToTimerangeArray(): TimeRange[] {
  return props.list.map((item) => {
    return [item.startTime, item.endTime] as TimeRange
  })
}
function clickAdd() {
  if (unref(disabled))
    return
  checkErrors()
  if (hasError())
    return
  emits('add', {
    startTime: '',
    endTime: '',
    type: props.type,
    price: Number(unref(price)) || '',
  })
  // 添加一项后添加一个error（false）
  setErrors(unref(errors).concat(false))
}
function clickRemove(index: number) {
  if (unref(disabled))
    return
  emits('remove', index)
  // 删除一项后删除一个error
  setErrors(unref(errors).filter((_, i) => i !== index))
}
function changeTimePicker(index?: number, timerange?: TimeRange) {
  // ElTimePicker 组件在 clear 时 modelValue 为 null
  if (!timerange && index != null) {
    unref(timerangeArray)[index] = ['', '']
  }
  checkErrors()
  emits('change', {
    index,
    timerange,
    configs: unref(configs),
  })
}

function checkErrors() {
  const { priceError, errors } = getErrors()
  setPriceError(priceError)
  setErrors(errors)
}
function resetErrors() {
  setPriceError(false)
  setErrors([])
}
function hasError() {
  return unref(errors).some(v => v) || unref(priceError)
}
function getErrors() {
  return {
    priceError: unref(checked) && !unref(price),
    errors: !unref(checked) ? [] : unref(timerangeArray).map(v => !(v.length === 2 && !!v[0] && !!v[1])),
  }
}
function isChecked() {
  return unref(checked)
}

watch(
  [
    () => unref(checked),
    () => unref(price),
  ],
  () => {
    checkErrors()
    if (!unref(checked)) {
      resetErrors()
    }
    emits('change', {
      configs: unref(configs),
    })
  },
)
watchEffect(() => {
  timerangeArray.value = listToTimerangeArray()
})

defineExpose({
  checkErrors,
  hasError,
  resetErrors,
  getErrors,
  isChecked,
})
</script>

<template>
  <div class="margin-left-sm margin-right-sm electricity-list mt-4 flex">
    <ElCheckbox v-model="checked">
      {{ typeText }}
    </ElCheckbox>
    <div class="margin-left-sm electricity-list-config relative flex-1 overflow-hidden">
      <div
        class="electricity-list-config-item relative flex items-center"
        :class="{ 'is-error': priceError }"
      >
        <span class="electricity-list-config-span label">价格：</span>
        <ElInput
          v-model="price"
          :disabled="disabled"
          input-style="padding-right: 80px;padding-left: 50px;"
          style="width: 300px;"
        />
        <span class="electricity-list-config-span unit">元/千瓦时</span>
      </div>
      <TransitionGroup name="list">
        <div
          v-for="(item, index) in timerangeArray" :key="index"
          class="electricity-list-config-item mt-4 flex items-center"
          :class="{ 'is-error': errors[index] }"
        >
          <ElTimePicker
            v-model="timerangeArray[index]![0]"
            class="free"
            placeholder="起始时间"
            value-format="HH:mm"
            format="HH:mm"
            clearable
            :disabled="disabled"
            @change="changeTimePicker(index, timerangeArray[index])"
          />
          <span class="fs-14" style="margin: 0 10px;">至</span>
          <ElTimePicker
            v-model="timerangeArray[index]![1]"
            class="free"
            placeholder="结束时间"
            value-format="HH:mm"
            format="HH:mm"
            clearable
            :disabled="disabled"
            @change="changeTimePicker(index, timerangeArray[index])"
          />
          <ElIcon
            v-if="index === 0"
            :size="22" class="ml-4 cursor-pointer"
            @click="clickAdd"
          >
            <CirclePlus />
          </ElIcon>
          <ElIcon
            v-else
            :size="22" class="ml-4 cursor-pointer" color="var(--el-color-danger)"
            @click="clickRemove(index)"
          >
            <Remove />
          </ElIcon>
        </div>
      </TransitionGroup>
    </div>
  </div>
</template>

<style lang="scss">
.electricity-list-config-span {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  white-space: nowrap;
  font-size: calc(var(--el-font-size-base) * 0.85);
  color: var(--el-text-color-secondary);
  &.label {
    left: 1rem;
    z-index: 1;
  }
  &.unit {
    left: 230px;
  }
}
.electricity-list-config-item {
  position: relative;
  &:before {
    content: '*';
    margin-right: 5px;
    color: var(--el-color-danger);
  }
  &.is-error {
    .el-input__wrapper {
      box-shadow: 0 0 0 1px var(--el-color-danger) inset;
    }
  }
}
</style>
